<script setup lang='ts'>
  import { nextTick, reactive, ref } from 'vue';
  import { gamesApi } from '@/api/controller';
  import { ToastSuccess, ToastWarning, Toastloading, allNumber, copyText } from '@/utils/public';
  import xmUpload from '@/components/Upload/xm-upload.vue';
  const formLabelWidth = '120px'
  const dataForm = ref()
  const $emit = defineEmits(['updateList'])
  const action = reactive({
    dialogFormVisible:false,
    disabled:false,
    title:'',
    gameTypeList:[] as Array<any>,
    formArr:[] as Array<any>,
    ruleArrString:''
  })
  interface formQuert {
    id:number
    custom_id:number
    rule:string
  }
  let form = reactive({} as formQuert)
  const formRules = {
    rule: [{ required: true, message: "请输入活动规则", trigger: "blur" }],
  }
  const hadleCopy = ()=>{
    copyText(JSON.stringify(action.formArr))
  }
  const handleRuleTitle = ()=>{
    action.formArr.push({
      Heading:'',
      ruleList:[{
        subtitle:'',
        ruleinfo:[{
          dt:'',
          ddList:[{
            dd:'',
          }]
        }]
      }]
    })
  }
  /**
   * 新增子标题
   * @param item 表单对象
   */
  const addHeading = (item:any = {})=>{
    item.ruleList.push({
      subtitle:'',
      ruleinfo:[
        {
          dt:'',
          ddList:[{
            dd:'',
          }]
        }
      ]
    })
  }
  /**
   * 新增规则类型
   * @param item 表单对象
   */
  const addSubtitle = (item:any = {})=>{
    item.ruleinfo.push({
      dt:'',
      ddList:[{
        dd:'',
      }]
    })
  }
  /**
   * 新增规则内容
   * @param item 表单对象
   */
  const addRuleDD = (item:any = {})=>{
    item.ddList.push({
      dd:'',
    })
  }
  /**
   * 增加换行标识
   * @param form 表单对象
   * @param text 追加字段
   */
  const handleAddBr = (form:any = {},text:string = '')=>{
    form[text] += '<br />'
  }
  /**
   * 粘贴规则JOSN
   */
  const handleRuleStickup = ()=>{
    if(action.ruleArrString) {
      action.formArr = JSON.parse(action.ruleArrString)
    } else {
      ToastWarning('请将复制的规则JOSN输入在输入框后点击粘贴按钮')
    }
  }
  const handleSubmit = ()=>{
    dataForm.value.validate(async(valid:any)=>{
      if(!valid) return
      let submitSet = false
      form.rule = JSON.stringify(action.formArr)
      const { id } = form
      const loading = Toastloading()
      if(id) {
        await gamesApi.customRuleEdit(form).then(()=>{
          ToastSuccess('编辑成功')
          submitSet = true
        }).catch(()=>{
          loading.close()
        })
      }
      else {
        await gamesApi.customRuleAdd(form).then(()=>{
          ToastSuccess('新增成功')
          submitSet = true
        }).catch(()=>{
          loading.close()
        })
      }
      if(submitSet) {
        loading.close()
        $emit('updateList')
        closeDialog()
      }
    })
  }
  const openDialog = async(query:any={})=> {
    const {
      id=0, custom_id=0, rule=''
    } = query
    if(!custom_id) return ToastWarning('缺少活动ID')
    const obj = {
      custom_id, rule
    } as any
    if(id) obj['id'] = id
    if(rule != '') action.formArr = JSON.parse(rule)
    Object.assign(form,obj)
    action.dialogFormVisible = true
    action.title = id?`编辑活动规则`:'创建活动规则'
  }
  const romoveForm = ()=>{
    action.ruleArrString = ''
    action.formArr = []
  }
  const closeDialog = ()=>{
    form = reactive({} as formQuert)
    nextTick(() => {
      dataForm.value.clearValidate();
    });
    action.dialogFormVisible = false
  }
  defineExpose({
    openDialog
  })
</script>

<template>
  <div>
    <el-dialog
      top="10vh"
      class="xm-dialog input-width xm-dialog-cont-y"
      v-model="action.dialogFormVisible"
      :close-on-click-modal="action.disabled"
      :show-close="action.disabled"
      :close-on-press-escape="action.disabled"
      width="55%"
      :title="action.title">
      <div class="flex-align-between">
        <div>
          <el-input
            v-model="action.ruleArrString"
            type="text"
            placeholder="请输入规则类型"
          />
          <el-button class="xm-ml10" type="primary" @click="handleRuleStickup">粘贴规则JSON</el-button>
        </div>
        <div style="width: max-content;">
          <el-button type="primary" @click="handleRuleTitle">新增主标题</el-button>
          <el-button type="primary" @click="hadleCopy">复制规则JSON</el-button>
          <el-button type="danger" @click="romoveForm">清空表单</el-button>
        </div>
      </div>
      <el-form ref="dataForm" :model="form" :rules="formRules">
        <div v-for="(item,formKey) in action.formArr" style="border-bottom: 1px dashed #ddd; margin-bottom: 40px; padding-bottom: 20px;">
          <el-form-item class="xm-mt10" :label-width="formLabelWidth" label="主标题">
            <xmUpload v-model:file-url="item.Heading" />
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="">
            <el-button type="primary" @click="addHeading(item)">新增子标题</el-button>
            <el-button type="danger" @click="()=>{ action.formArr.splice(formKey,1) }">删除主标题</el-button>
          </el-form-item>
          <template v-for="(rule,ruleKey) in item.ruleList">
            <el-form-item :label-width="formLabelWidth" label="子标题">
              <el-input
                :disabled="action.disabled"
                v-model="rule.subtitle"
                type="text"
                placeholder="请输入规则类型"
              />
              <el-button class="xm-ml10" type="primary" @click="addSubtitle(rule)">新增规则类型</el-button>
              <el-button type="danger" @click="()=>{ item.ruleList.splice(ruleKey,1) }">删除</el-button>
            </el-form-item>
            <template v-for="(ruleText,ruleTextKey) in rule.ruleinfo">
              <el-form-item :label-width="formLabelWidth" label="规则类型">
                <el-input
                  :disabled="action.disabled"
                  v-model="ruleText.dt"
                  type="text"
                  placeholder="请输入规则类型"
                />
                <el-button class="xm-ml10" type="primary" @click="addRuleDD(ruleText)">新增规则内容</el-button>
                <el-button class="xm-ml10" type="danger" @click="()=>{ rule.ruleinfo.splice(ruleTextKey,1) }">删除</el-button>
              </el-form-item>
              <el-form-item v-for="(ddinfo,ddKey) in ruleText.ddList" :label-width="formLabelWidth" label="规则内容">
                <el-input
                  :disabled="action.disabled"
                  v-model="ddinfo.dd"
                  :autosize="{ minRows: 4, maxRows: 4}"
                  type="textarea"
                  placeholder="请输入规则内容"
                />
                 
                <!--  -->
                <div class="xm-mt10">
                  <el-button type="danger" @click="()=>{ ruleText.ddList.splice(ddKey,1) }">删除</el-button>
                </div>
              </el-form-item>
            </template>
          </template>
        </div>
      </el-form>
      <template v-if="!action.disabled" #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>